package casa.depesos.app.com.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import casa.depesos.app.com.databinding.ChooseItemBinding;

public class ChooseAdapter extends RecyclerView.Adapter {

    List list;
    int current;

    public ChooseAdapter(List list, int now) {
        this.list = list;
        current = now;
    }

    public void setList(List list, int now) {
        current = now;
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ChooseItemBinding binding = ChooseItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        ChooseItemBinding binding;

        Holder(ChooseItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            bindHolder(this, p);
        }
    }

    protected void bindHolder(Holder holder, int p) {
        holder.binding.title.setText(list.get(p).toString());
        holder.binding.img.setVisibility(p == current ? View.VISIBLE : View.INVISIBLE);
        holder.itemView.setOnClickListener(view -> {
            int tmp = holder.getBindingAdapterPosition();
            if (current == tmp) {
                return;
            }
            current = tmp;
            notifyDataSetChanged();
        });
    }

    public int getCurrent() {
        return current;
    }
}
